package handlers

import (
	"brood-agent2/utils"
	"fmt"
	"os"
	"path/filepath"
)

func InstallDockerImpl(installer DockerInstaller) error {
	utils.Logger.Info("install docker begin")

	err := installCheck("docker.service")
	if err != nil {
		return err
	}

	pkgName := "docker"
	// 下载解压
	err = extractPkg(installer.PkgUrl.Url, installer.ApplicationDir, installer.PkgUrl.ExtractType, pkgName)
	if err != nil {
		return err
	}

	// 创建软连接
	dirList, err := utils.GetDirDetailList(filepath.Join(installer.ApplicationDir, pkgName), "")
	if err != nil {
		return err
	}
	for _, dirEntry := range dirList {
		if !dirEntry.IsDir() {
			n := dirEntry.Name()
			err = addSoftLink(filepath.Join(installer.ApplicationDir, "docker", fmt.Sprintf("%s", n)), fmt.Sprintf("/usr/bin/%s", n))
			if err != nil {
				return err
			}
		}
	}

	// 下载所需配置
	utils.Logger.Info("download depend files")
	for _, download := range installer.DependFiles {
		err = utils.DownloadFile(download.Url, download.SavePath, os.FileMode(0755), false)
		if err != nil {
			return err
		}
	}

	err = utils.RegisterService("docker.service")
	if err != nil {
		return err
	}

	utils.Logger.Info("install docker done")

	return nil

}
